package com.liaoban.app.update;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.liaoban.app.R;
import com.liaoban.app.api.type.comment.BaseResponse;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.ConfigKey;
import com.liaoban.app.helper.ConfigHelper;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.util.RxUtils;
import com.liaoban.app.widget.MyAlertDialog;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * Created by ybc on 2017/10/13 0023.
 * 更新
 */
public class UpdateHelper implements ApkUpdateConstants {

    private boolean isInRequesting;
    private static UpdateServiceFinishCallback sUpdateServiceFinishCallback;
    private static UpdateHelper mUpdateHelper;

    private UpdateHelper() {
        sUpdateServiceFinishCallback = new UpdateFinishCallback();
    }

    public static UpdateHelper getInstance() {
        if (null == mUpdateHelper) {
            synchronized (UpdateHelper.class) {
                if (null == mUpdateHelper) {
                    mUpdateHelper = new UpdateHelper();
                }
            }
        }
        return mUpdateHelper;
    }

    public void doUpdateCheckRequest(final Context context, final boolean feedbackMsg) {
        if (isInRequesting()) {
            if (feedbackMsg) {
                ToastHelper.show(context, R.string.update_in_updating);
            }
            return;
        }
        setInRequesting(true);
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = null;
        int version = 0;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            version = packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.setVersion_num("11");
        CommonBiz.getInstance().version(updateRequest).compose(RxUtils.ioToMainTread()).subscribe(new Observer<BaseResponse<UpdateResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse<UpdateResponse> updateResponse) {
                ConfigHelper.save(context, ConfigKey.VERSION_CHECK, updateResponse.version_check + "");
                if (1 == updateResponse.code) {
                    String msg = null;
                    if (TextUtils.isEmpty(updateResponse.data.getVersion_text())) {
                        msg = context.getString(R.string.update_dlg_msg_null,
                                updateResponse.data.getVersion_size());
                    } else {
                        msg = context.getString(R.string.update_dlg_msg,
                                updateResponse.data.getVersion_size(), updateResponse.data.getVersion_text());
                    }
                    new MyAlertDialog(context).builder().setMsg(msg).
                            setPositiveButton("立即更新", view -> downloadApkWithNotification(context, updateResponse.data.getVersion_url(), true, sUpdateServiceFinishCallback))
                            .setNegativeButton("暂不更新", null).show();
                } else {
                    if (feedbackMsg) {
                        ToastHelper.show(context, updateResponse.msg);
                    }
                }
                setInRequesting(false);
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
                setInRequesting(false);
            }

            @Override
            public void onComplete() {

            }
        });

    }


    public boolean isInRequesting() {
        return isInRequesting;
    }

    public void setInRequesting(boolean isInRequesting) {
        this.isInRequesting = isInRequesting;
    }

    private void downloadApkWithNotification(Context context, String apkUrl, boolean installedAutomaticlly, UpdateServiceFinishCallback updateServiceFinishCallback) {
        Intent intent = new Intent(context.getApplicationContext(), UpdateService.class);
        intent.putExtra(BUNDLE_KEY_APK_DOWNLOAD_URL, apkUrl);
        intent.putExtra(BUNDLE_KEY_INSTALLED_AUTOMATICLLY, installedAutomaticlly);
        intent.putExtra(BUNDLE_KEY_FINISH_CALLBACK, updateServiceFinishCallback);
        context.startService(intent);
    }

}
